<?php
class MemcacheCache {
    private static $memcache = null;
    private static $isMemcache = true;
    public function __construct() {
        self::$memcache = new Memcache();
        $cacheServer = Config::get('MEMCACHE_SERVER');
        if(false == Config::get('MEMCACHE_SERVER'))
            throw new Exception("MEMCACHE_SERVER没有设置");
        if (false == is_array($cacheServer)) {
            $this->addServer($cacheServer);
        } else if (is_array($cacheServer)) {
            foreach ($cacheServer as $server) {
                $this->addServer($server);
            }
        }
    }
    
    private function addServer($server) {
        list($serverHost, $serverPort) = explode(':', $server);
        $serverPort = $serverPort ? $serverPort : 11211;
        self::$memcache->addServer($serverHost, $serverPort);
    }
    
    public function set($key, $value, $expire=0) {
        if($expire != 0)
            $expire = $expire > time() ? $expire : time() + $expire;
        $cacheData = array('expire'=>$expire,
                           'value'=>$value);
        $compressed = Config::get('CACHE_COMPRESSED')? MEMCACHE_COMPRESSED : 0;
        return self::$memcache->set($key, serialize($cacheData), $compressed, $expire=0);
    }
    
    public function get($key) {
        $cacheContents = self::$memcache->get($key);
        $cacheData = unserialize($cacheContents);
        if(abs($cacheData['expire']) > 0 && $cacheData['expire'] <= time()) {
            return null;
        }
        return $cacheData['value'];
    }
    
    public function delete($key) {
        if (is_array($key)) {
            foreach($key as $dk=>$keySet) 
                $this->delete($dk);
            return true;
        }
        return self::$memcache->delete($key);
    }
    
    public function close() {
        return self::$memcache->close();
    }
}
?>